home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perlfaq6.Z / perlfaq6
Encoding:
Text File  |  1998-10-28  |  33.9 KB  |  925 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perlfaq6 - Regexps ($Revision: 1.22 $, $Date:    1998/07/16
  10.       14:01:07 $)
  11.  
  12.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  13.       This section is surprisingly small because the rest of the
  14.       FAQ is littered with answers involving regular expressions.
  15.       For example, decoding    a URL and checking whether something
  16.       is a number are handled with regular expressions, but    those
  17.       answers are found elsewhere in this document (in the section
  18.       on Data and the Networking one on networking,    to be
  19.       precise).
  20.  
  21.       HHHHoooowwww ccccaaaannnn IIII hhhhooooppppeeee ttttoooo uuuusssseeee    rrrreeeegggguuuullllaaaarrrr    eeeexxxxpppprrrreeeessssssssiiiioooonnnnssss wwwwiiiitttthhhhoooouuuutttt ccccrrrreeeeaaaattttiiiinnnngggg
  22.       iiiilllllllleeeeggggiiiibbbblllleeee aaaannnndddd    uuuunnnnmmmmaaaaiiiinnnnttttaaaaiiiinnnnaaaabbbblllleeee ccccooooddddeeee????
  23.  
  24.       Three    techniques can make regular expressions    maintainable
  25.       and understandable.
  26.  
  27.       Comments Outside the Regexp
  28.           Describe what you're doing and how you're    doing it,
  29.           using normal Perl    comments.
  30.  
  31.           # turn the line into the first word, a colon,    and the
  32.           # number of characters on the    rest of    the line
  33.           s/^(\w+)(.*)/    lc($1) . ":" . length($2) /meg;
  34.  
  35.  
  36.       Comments Inside the Regexp
  37.           The /x modifier causes whitespace    to be ignored in a
  38.           regexp pattern (except in    a character class), and    also
  39.           allows you to use    normal comments    there, too.  As    you
  40.           can imagine, whitespace and comments help    a lot.
  41.  
  42.           /x lets you turn this:
  43.  
  44.           s{<(?:[^>'"]*|".*?"|'.*?')+>}{}gs;
  45.  
  46.           into this:
  47.  
  48.           s{ <              # opening angle bracket
  49.               (?:          # Non-backreffing grouping paren
  50.                [^>'"] *      # 0 or more things that are neither >    nor ' nor "
  51.                   |          #    or else
  52.                ".*?"      # a section between double quotes (stingy match)
  53.                   |          #    or else
  54.                '.*?'      # a section between single quotes (stingy match)
  55.               )    +          #   all occurring one    or more    times
  56.              >              # closing angle bracket
  57.           }{}gsx;          # replace with nothing, i.e. delete
  58.  
  59.           It's still not quite so clear as prose, but it is    very
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  71.  
  72.  
  73.  
  74.           useful for describing the    meaning    of each    part of    the
  75.           pattern.
  76.  
  77.       Different Delimiters
  78.           While we normally    think of patterns as being delimited
  79.           with / characters, they can be delimited by almost any
  80.           character.  the _p_e_r_l_r_e manpage describes this.  For
  81.           example, the s///    above uses braces as delimiters.
  82.           Selecting    another    delimiter can avoid quoting the
  83.           delimiter    within the pattern:
  84.  
  85.           s/\/usr\/local/\/usr\/share/g;      #    bad delimiter choice
  86.           s#/usr/local#/usr/share#g;          #    better
  87.  
  88.  
  89.       IIII''''mmmm hhhhaaaavvvviiiinnnngggg ttttrrrroooouuuubbbblllleeee mmmmaaaattttcccchhhhiiiinnnngggg oooovvvveeeerrrr mmmmoooorrrreeee    tttthhhhaaaannnn oooonnnneeee lllliiiinnnneeee....    WWWWhhhhaaaatttt''''ssss
  90.       wwwwrrrroooonnnngggg????
  91.  
  92.       Either you don't have    more than one line in the string
  93.       you're looking at (probably),    or else    you aren't using the
  94.       correct _m_o_d_i_f_i_e_r(s) on your pattern (possibly).
  95.  
  96.       There    are many ways to get multiline data into a string.  If
  97.       you want it to happen    automatically while reading input,
  98.       you'll want to set $/    (probably to ''    for paragraphs or
  99.       undef    for the    whole file) to allow you to read more than one
  100.       line at a time.
  101.  
  102.       Read the _p_e_r_l_r_e manpage to help you decide which of /s and
  103.       /m (or both) you might want to use: /s allows    dot to include
  104.       newline, and /m allows caret and dollar to match next    to a
  105.       newline, not just at the end of the string.  You do need to
  106.       make sure that you've    actually got a multiline string    in
  107.       there.
  108.  
  109.       For example, this program detects duplicate words, even when
  110.       they span line breaks    (but not paragraph ones).  For this
  111.       example, we don't need /s because we aren't using dot    in a
  112.       regular expression that we want to cross line    boundaries.
  113.       Neither do we    need /m    because    we aren't wanting caret    or
  114.       dollar to match at any point inside the record next to
  115.       newlines.  But it's imperative that $/ be set    to something
  116.       other    than the default, or else we won't actually ever have
  117.       a multiline record read in.
  118.  
  119.           $/ = '';          # read in more whole paragraph, not just one line
  120.           while ( <> ) {
  121.           while    ( /\b([\w'-]+)(\s+\1)+\b/gi ) {      # word starts    alpha
  122.               print "Duplicate $1 at paragraph $.\n";
  123.           }
  124.           }
  125.  
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  137.  
  138.  
  139.  
  140.       Here's code that finds sentences that    begin with "From "
  141.       (which would be mangled by many mailers):
  142.  
  143.           $/ = '';          # read in more whole paragraph, not just one line
  144.           while ( <> ) {
  145.           while    ( /^From /gm ) { # /m makes ^ match next to \n
  146.               print "leading from in paragraph $.\n";
  147.           }
  148.           }
  149.  
  150.       Here's code that finds everything between START and END in a
  151.       paragraph:
  152.  
  153.           undef $/;          # read in whole file,    not just one line or paragraph
  154.           while ( <> ) {
  155.           while    ( /START(.*?)END/sm ) {    # /s makes . cross line    boundaries
  156.               print "$1\n";
  157.           }
  158.           }
  159.  
  160.  
  161.       HHHHoooowwww ccccaaaannnn IIII ppppuuuullllllll oooouuuutttt lllliiiinnnneeeessss bbbbeeeettttwwwweeeeeeeennnn ttttwwwwoooo ppppaaaatttttttteeeerrrrnnnnssss    tttthhhhaaaatttt aaaarrrreeee
  162.       tttthhhheeeemmmmsssseeeellllvvvveeeessss oooonnnn    ddddiiiiffffffffeeeerrrreeeennnntttt lllliiiinnnneeeessss????
  163.  
  164.       You can use Perl's somewhat exotic ..    operator (documented
  165.       in the _p_e_r_l_o_p    manpage):
  166.  
  167.           perl -ne 'print if /START/ .. /END/' file1 file2 ...
  168.  
  169.       If you wanted    text and not lines, you    would use
  170.  
  171.           perl -0777 -pe 'print "$1\n" while /START(.*?)END/gs' file1 file2    ...
  172.  
  173.       But if you want nested occurrences of    START through END,
  174.       you'll run up    against    the problem described in the question
  175.       in this section on matching balanced text.
  176.  
  177.       Here's another example of using ..:
  178.  
  179.           while (<>) {
  180.           $in_header =     1  .. /^$/;
  181.           $in_body   = /^$/ .. eof();
  182.           # now    choose between them
  183.           }    continue {
  184.           reset    if eof();      # fix    $.
  185.           }
  186.  
  187.  
  188.       IIII ppppuuuutttt    aaaa rrrreeeegggguuuullllaaaarrrr eeeexxxxpppprrrreeeessssssssiiiioooonnnn iiiinnnnttttoooo $$$$//// bbbbuuuutttt iiiitttt ddddiiiiddddnnnn''''tttt wwwwoooorrrrkkkk....
  189.       WWWWhhhhaaaatttt''''ssss wwwwrrrroooonnnngggg????
  190.  
  191.       $/ must be a string, not a regular expression.  Awk has to
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  203.  
  204.  
  205.  
  206.       be better for    something. :-)
  207.  
  208.       Actually, you    could do this if you don't mind    reading    the
  209.       whole    file into memory:
  210.  
  211.           undef $/;
  212.           @records = split /your_pattern/, <FH>;
  213.  
  214.       The Net::Telnet module (available from CPAN) has the
  215.       capability to    wait for a pattern in the input    stream,    or
  216.       timeout if it    doesn't    appear within a    certain    time.
  217.  
  218.           ## Create    a file with three lines.
  219.           open FH, ">file";
  220.           print FH "The first line\nThe second line\nThe third line\n";
  221.           close FH;
  222.  
  223.           ## Get a read/write filehandle to    it.
  224.           $fh = new    FileHandle "+<file";
  225.  
  226.           ## Attach    it to a    "stream" object.
  227.           use Net::Telnet;
  228.           $file = new Net::Telnet (-fhopen => $fh);
  229.  
  230.           ## Search    for the    second line and    print out the third.
  231.           $file->waitfor('/second line\n/');
  232.           print $file->getline;
  233.  
  234.  
  235.       HHHHoooowwww ddddoooo IIII ssssuuuubbbbssssttttiiiittttuuuutttteeee ccccaaaasssseeee iiiinnnnsssseeeennnnssssiiiittttiiiivvvveeeellllyyyy oooonnnn tttthhhheeee    LLLLHHHHSSSS,,,, bbbbuuuutttt
  236.       pppprrrreeeesssseeeerrrrvvvviiiinnnngggg ccccaaaasssseeee oooonnnn tttthhhheeee RRRRHHHHSSSS????
  237.  
  238.       It depends on    what you mean by "preserving case".  The
  239.       following script makes the substitution have the same    case,
  240.       letter by letter, as the original.  If the substitution has
  241.       more characters than the string being    substituted, the case
  242.       of the last character    is used    for the    rest of    the
  243.       substitution.
  244.  
  245.           #    Original by Nathan Torkington, massaged    by Jeffrey Friedl
  246.           #
  247.           sub preserve_case($$)
  248.           {
  249.           my ($old, $new) = @_;
  250.           my ($state) =    0; # 0 = no change; 1 =    lc; 2 =    uc
  251.           my ($i, $oldlen, $newlen, $c)    = (0, length($old), length($new));
  252.           my ($len) = $oldlen <    $newlen    ? $oldlen : $newlen;
  253.  
  254.  
  255.  
  256.  
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  269.  
  270.  
  271.  
  272.           for ($i = 0; $i < $len; $i++)    {
  273.               if ($c = substr($old, $i,    1), $c =~ /[\W\d_]/) {
  274.               $state = 0;
  275.               }    elsif (lc $c eq    $c) {
  276.               substr($new, $i, 1) =    lc(substr($new,    $i, 1));
  277.               $state = 1;
  278.               }    else {
  279.               substr($new, $i, 1) =    uc(substr($new,    $i, 1));
  280.               $state = 2;
  281.               }
  282.           }
  283.           # finish up with any remaining new (for when new is longer than old)
  284.           if ($newlen >    $oldlen) {
  285.               if ($state == 1) {
  286.               substr($new, $oldlen)    = lc(substr($new, $oldlen));
  287.               }    elsif ($state == 2) {
  288.               substr($new, $oldlen)    = uc(substr($new, $oldlen));
  289.               }
  290.           }
  291.           return $new;
  292.           }
  293.  
  294.           $a = "this is a TEsT case";
  295.           $a =~ s/(test)/preserve_case($1, "success")/gie;
  296.           print "$a\n";
  297.  
  298.       This prints:
  299.  
  300.           this is a    SUcCESS    case
  301.  
  302.  
  303.       HHHHoooowwww ccccaaaannnn IIII mmmmaaaakkkkeeee \\\\wwww match national character sets?
  304.  
  305.       See the _p_e_r_l_l_o_c_a_l_e manpage.
  306.  
  307.       HHHHoooowwww ccccaaaannnn IIII mmmmaaaattttcccchhhh aaaa llllooooccccaaaalllleeee----ssssmmmmaaaarrrrtttt vvvveeeerrrrssssiiiioooonnnn ooooffff ////[[[[aaaa----zzzzAAAA----ZZZZ]]]]////?
  308.  
  309.       One alphabetic character would be /[^\W\d_]/,    no matter what
  310.       locale you're    in.  Non-alphabetics would be /[\W\d_]/
  311.       (assuming you    don't consider an underscore a letter).
  312.  
  313.       HHHHoooowwww ccccaaaannnn IIII qqqquuuuooootttteeee aaaa vvvvaaaarrrriiiiaaaabbbblllleeee ttttoooo    uuuusssseeee iiiinnnn aaaa rrrreeeeggggeeeexxxxpppp????
  314.  
  315.       The Perl parser will expand $variable    and @variable
  316.       references in    regular    expressions unless the delimiter is a
  317.       single quote.     Remember, too,    that the right-hand side of a
  318.       s/// substitution is considered a double-quoted string (see
  319.       the _p_e_r_l_o_p manpage for more details).     Remember also that
  320.       any regexp special characters    will be    acted on unless    you
  321.       precede the substitution with    \Q.  Here's an example:
  322.  
  323.  
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  335.  
  336.  
  337.  
  338.           $string =    "to die?";
  339.           $lhs = "die?";
  340.           $rhs = "sleep no more";
  341.  
  342.           $string =~ s/\Q$lhs/$rhs/;
  343.           #    $string    is now "to sleep no more"
  344.  
  345.       Without the \Q, the regexp would also    spuriously match "di".
  346.  
  347.       WWWWhhhhaaaatttt iiiissss ////oooo really for?
  348.  
  349.       Using    a variable in a    regular    expression match forces    a re-
  350.       evaluation (and perhaps recompilation) each time through.
  351.       The /o modifier locks    in the regexp the first    time it's
  352.       used.     This always happens in    a constant regular expression,
  353.       and in fact, the pattern was compiled    into the internal
  354.       format at the    same time your entire program was.
  355.  
  356.       Use of /o is irrelevant unless variable interpolation    is
  357.       used in the pattern, and if so, the regexp engine will
  358.       neither know nor care    whether    the variables change after the
  359.       pattern is evaluated the _v_e_r_y    _f_i_r_s_t time.
  360.  
  361.       /o is    often used to gain an extra measure of efficiency by
  362.       not performing subsequent evaluations    when you know it won't
  363.       matter (because you know the variables won't change),    or
  364.       more rarely, when you    don't want the regexp to notice    if
  365.       they do.
  366.  
  367.       For example, here's a    "paragrep" program:
  368.  
  369.           $/ = '';    # paragraph mode
  370.           $pat = shift;
  371.           while (<>) {
  372.           print    if /$pat/o;
  373.           }
  374.  
  375.  
  376.       HHHHoooowwww ddddoooo IIII uuuusssseeee aaaa rrrreeeegggguuuullllaaaarrrr eeeexxxxpppprrrreeeessssssssiiiioooonnnn ttttoooo ssssttttrrrriiiipppp CCCC ssssttttyyyylllleeee ccccoooommmmmmmmeeeennnnttttssss
  377.       ffffrrrroooommmm aaaa ffffiiiilllleeee????
  378.  
  379.       While    this actually can be done, it's    much harder than you'd
  380.       think.  For example, this one-liner
  381.  
  382.           perl -0777 -pe 's{/\*.*?\*/}{}gs'    foo.c
  383.  
  384.       will work in many but    not all    cases.    You see, it's too
  385.       simple-minded    for certain kinds of C programs, in
  386.       particular, those with what appear to    be comments in quoted
  387.       strings.  For    that, you'd need something like    this, created
  388.       by Jeffrey Friedl:
  389.  
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  401.  
  402.  
  403.  
  404.           $/ = undef;
  405.           $_ = <>;
  406.           s#/\*[^*]*\*+([^/*][^*]*\*+)*/|("(\\.|[^"\\])*"|'(\\.|[^'\\])*'|\n+|.[^/"'\\]*)#$2#g;
  407.           print;
  408.  
  409.       This could, of course, be more legibly written with the /x
  410.       modifier, adding whitespace and comments.
  411.  
  412.       CCCCaaaannnn IIII    uuuusssseeee PPPPeeeerrrrllll rrrreeeegggguuuullllaaaarrrr eeeexxxxpppprrrreeeessssssssiiiioooonnnnssss ttttoooo    mmmmaaaattttcccchhhh bbbbaaaallllaaaannnncccceeeedddd tttteeeexxxxtttt????
  413.  
  414.       Although Perl    regular    expressions are    more powerful than
  415.       "mathematical" regular expressions, because they feature
  416.       conveniences like backreferences (\1 and its ilk), they
  417.       still    aren't powerful    enough.    You still need to use non-
  418.       regexp techniques to parse balanced text, such as the    text
  419.       enclosed between matching parentheses    or braces, for
  420.       example.
  421.  
  422.       An elaborate subroutine (for 7-bit ASCII only) to pull out
  423.       balanced and possibly    nested single chars, like ` and    ', {
  424.       and }, or ( and ) can    be found in
  425.       http://www.perl.com/CPAN/authors/id/TOMC/scripts/pull_quotes.gz
  426.       .
  427.  
  428.       The C::Scan module from CPAN contains    such subs for internal
  429.       usage, but they are undocumented.
  430.  
  431.       WWWWhhhhaaaatttt ddddooooeeeessss iiiitttt mmmmeeeeaaaannnn tttthhhhaaaatttt rrrreeeeggggeeeexxxxppppssss aaaarrrreeee ggggrrrreeeeeeeeddddyyyy????  HHHHoooowwww ccccaaaannnn IIII    ggggeeeetttt
  432.       aaaarrrroooouuuunnnndddd iiiitttt????
  433.  
  434.       Most people mean that    greedy regexps match as    much as    they
  435.       can.    Technically speaking, it's actually the    quantifiers
  436.       (?, *, +, {})    that are greedy    rather than the    whole pattern;
  437.       Perl prefers local greed and immediate gratification to
  438.       overall greed.  To get non-greedy versions of    the same
  439.       quantifiers, use (??,    *?, +?,    {}?).
  440.  
  441.       An example:
  442.  
  443.           $s1 =    $s2 = "I am very very cold";
  444.           $s1 =~ s/ve.*y //;      # I am cold
  445.           $s2 =~ s/ve.*?y //;      # I am very cold
  446.  
  447.       Notice how the second    substitution stopped matching as soon
  448.       as it    encountered "y ".  The *? quantifier effectively tells
  449.       the regular expression engine    to find    a match    as quickly as
  450.       possible and pass control on to whatever is next in line,
  451.       like you would if you    were playing hot potato.
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  467.  
  468.  
  469.  
  470.       HHHHoooowwww ddddoooo IIII pppprrrroooocccceeeessssssss eeeeaaaacccchhhh    wwwwoooorrrrdddd oooonnnn    eeeeaaaacccchhhh lllliiiinnnneeee????
  471.  
  472.       Use the split    function:
  473.  
  474.           while (<>) {
  475.           foreach $word    ( split    ) {
  476.               #    do something with $word    here
  477.           }
  478.           }
  479.  
  480.       Note that this isn't really a    word in    the English sense;
  481.       it's just chunks of consecutive non-whitespace characters.
  482.  
  483.       To work with only alphanumeric sequences, you    might consider
  484.  
  485.           while (<>) {
  486.           foreach $word    (m/(\w+)/g) {
  487.               #    do something with $word    here
  488.           }
  489.           }
  490.  
  491.  
  492.       HHHHoooowwww ccccaaaannnn IIII pppprrrriiiinnnntttt oooouuuutttt aaaa    wwwwoooorrrrdddd----ffffrrrreeeeqqqquuuueeeennnnccccyyyy oooorrrr lllliiiinnnneeee----ffffrrrreeeeqqqquuuueeeennnnccccyyyy
  493.       ssssuuuummmmmmmmaaaarrrryyyy????
  494.  
  495.       To do    this, you have to parse    out each word in the input
  496.       stream.  We'll pretend that by word you mean chunk of
  497.       alphabetics, hyphens,    or apostrophes,    rather than the    non-
  498.       whitespace chunk idea    of a word given    in the previous
  499.       question:
  500.  
  501.           while (<>) {
  502.           while    ( /(\b[^\W_\d][\w'-]+\b)/g ) {     # misses "`sheep'"
  503.               $seen{$1}++;
  504.           }
  505.           }
  506.           while ( ($word, $count) =    each %seen ) {
  507.           print    "$count    $word\n";
  508.           }
  509.  
  510.       If you wanted    to do the same thing for lines,    you wouldn't
  511.       need a regular expression:
  512.  
  513.           while (<>) {
  514.           $seen{$_}++;
  515.           }
  516.           while ( ($line, $count) =    each %seen ) {
  517.           print    "$count    $line";
  518.           }
  519.  
  520.       If you want these output in a    sorted order, see the section
  521.       on Hashes.
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  533.  
  534.  
  535.  
  536.       HHHHoooowwww ccccaaaannnn IIII ddddoooo aaaapppppppprrrrooooxxxxiiiimmmmaaaatttteeee mmmmaaaattttcccchhhhiiiinnnngggg????
  537.  
  538.       See the module String::Approx    available from CPAN.
  539.  
  540.       HHHHoooowwww ddddoooo IIII eeeeffffffffiiiicccciiiieeeennnnttttllllyyyy mmmmaaaattttcccchhhh mmmmaaaannnnyyyy rrrreeeegggguuuullllaaaarrrr eeeexxxxpppprrrreeeessssssssiiiioooonnnnssss aaaatttt oooonnnncccceeee????
  541.  
  542.       The following    is super-inefficient:
  543.  
  544.           while (<FH>) {
  545.           foreach $pat (@patterns) {
  546.               if ( /$pat/ ) {
  547.               # do something
  548.               }
  549.           }
  550.           }
  551.  
  552.       Instead, you either need to use one of the experimental
  553.       Regexp extension modules from    CPAN (which might well be
  554.       overkill for your purposes), or else put together something
  555.       like this, inspired from a routine in    Jeffrey    Friedl's book:
  556.  
  557.           sub _bm_build {
  558.           my $condition    = shift;
  559.           my @regexp = @_;  # this MUST    not be local();    need my()
  560.           my $expr = join $condition =>    map { "m/\$regexp[$_]/o" } (0..$#regexp);
  561.           my $match_func = eval    "sub { $expr }";
  562.           die if $@;  #    propagate $@; this shouldn't happen!
  563.           return $match_func;
  564.           }
  565.  
  566.           sub bm_and { _bm_build('&&', @_) }
  567.           sub bm_or     { _bm_build('||', @_) }
  568.  
  569.           $f1 = bm_and qw{
  570.               xterm
  571.               (?i)window
  572.           };
  573.  
  574.           $f2 = bm_or qw{
  575.               \b[Ff]ree\b
  576.               \bBSD\B
  577.               (?i)sys(tem)?\s*[V5]\b
  578.           };
  579.  
  580.           #    feed me    /etc/termcap, prolly
  581.           while ( <> ) {
  582.           print    "1: $_"    if &$f1;
  583.           print    "2: $_"    if &$f2;
  584.           }
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  599.  
  600.  
  601.  
  602.       WWWWhhhhyyyy ddddoooonnnn''''tttt wwwwoooorrrrdddd----bbbboooouuuunnnnddddaaaarrrryyyy sssseeeeaaaarrrrcccchhhheeeessss wwwwiiiitttthhhh    \\\\bbbb work    for me?
  603.  
  604.       Two common misconceptions are    that \b    is a synonym for \s+,
  605.       and that it's    the edge between whitespace characters and
  606.       non-whitespace characters.  Neither is correct.  \b is the
  607.       place    between    a \w character and a \W    character (that    is, \b
  608.       is the edge of a "word").  It's a zero-width assertion, just
  609.       like ^, $, and all the other anchors,    so it doesn't consume
  610.       any characters.  the _p_e_r_l_r_e manpage describes    the behaviour
  611.       of all the regexp metacharacters.
  612.  
  613.       Here are examples of the incorrect application of \b,    with
  614.       fixes:
  615.  
  616.           "two words" =~ /(\w+)\b(\w+)/;          #    WRONG
  617.           "two words" =~ /(\w+)\s+(\w+)/;          #    right
  618.  
  619.           "    =matchless= text" =~ /\b=(\w+)=\b/;   #    WRONG
  620.           "    =matchless= text" =~ /=(\w+)=/;          #    right
  621.  
  622.       Although they    may not    do what    you thought they did, \b and
  623.       \B can still be quite    useful.     For an    example    of the correct
  624.       use of \b, see the example of    matching duplicate words over
  625.       multiple lines.
  626.  
  627.       An example of    using \B is the    pattern    \Bis\B.     This will
  628.       find occurrences of "is" on the insides of words only, as in
  629.       "thistle", but not "this" or "island".
  630.  
  631.       WWWWhhhhyyyy ddddooooeeeessss uuuussssiiiinnnngggg $$$$&&&&,,,, $$$$````,,,, oooorrrr $$$$'''' sssslllloooowwww mmmmyyyy pppprrrrooooggggrrrraaaammmm ddddoooowwwwnnnn????
  632.  
  633.       Because once Perl sees that you need one of these variables
  634.       anywhere in the program, it has to provide them on each and
  635.       every    pattern    match.    The same mechanism that    handles    these
  636.       provides for the use of $1, $2, etc.,    so you pay the same
  637.       price    for each regexp    that contains capturing    parentheses.
  638.       But if you never use $&, etc., in your script, then regexps
  639.       _w_i_t_h_o_u_t capturing parentheses    won't be penalized. So avoid
  640.       $&, $', and $` if you    can, but if you    can't (and some
  641.       algorithms really appreciate them), once you've used them
  642.       once,    use them at will, because you've already paid the
  643.       price.
  644.  
  645.       WWWWhhhhaaaatttt ggggoooooooodddd iiiissss \\\\GGGG in a regular expression?
  646.  
  647.       The notation \G is used in a match or    substitution in
  648.       conjunction the /g modifier (and ignored if there's no /g)
  649.       to anchor the    regular    expression to the point    just past
  650.       where    the last match occurred, i.e. the _p_o_s()    point.
  651.  
  652.       For example, suppose you had a line of text quoted in
  653.       standard mail    and Usenet notation, (that is, with leading >
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  665.  
  666.  
  667.  
  668.       characters), and you want change each    leading    > into a
  669.       corresponding    :.  You    could do so in this way:
  670.  
  671.            s/^(>+)/':' x length($1)/gem;
  672.  
  673.       Or, using \G,    the much simpler (and faster):
  674.  
  675.           s/\G>/:/g;
  676.  
  677.       A more sophisticated use might involve a tokenizer.  The
  678.       following lex-like example is    courtesy of Jeffrey Friedl.
  679.       It did not work in 5.003 due to bugs in that release,    but
  680.       does work in 5.004 or    better.     (Note the use of /c, which
  681.       prevents a failed match with /g from resetting the search
  682.       position back    to the beginning of the    string.)
  683.  
  684.           while (<>) {
  685.         chomp;
  686.         PARSER:    {
  687.              m/    \G( \d+\b    )/gcx    && do { print "number: $1\n";  redo; };
  688.              m/    \G( \w+         )/gcx    && do { print "word:   $1\n";  redo; };
  689.              m/    \G( \s+         )/gcx    && do { print "space:  $1\n";  redo; };
  690.              m/    \G( [^\w\d]+ )/gcx    && do { print "other:  $1\n";  redo; };
  691.         }
  692.           }
  693.  
  694.       Of course, that could    have been written as
  695.  
  696.           while (<>) {
  697.         chomp;
  698.         PARSER:    {
  699.              if    ( /\G( \d+\b    )/gcx  {
  700.               print    "number: $1\n";
  701.               redo PARSER;
  702.              }
  703.              if    ( /\G( \w+    )/gcx  {
  704.               print    "word: $1\n";
  705.               redo PARSER;
  706.              }
  707.              if    ( /\G( \s+    )/gcx  {
  708.               print    "space:    $1\n";
  709.               redo PARSER;
  710.              }
  711.              if    ( /\G( [^\w\d]+    )/gcx  {
  712.               print    "other:    $1\n";
  713.               redo PARSER;
  714.              }
  715.         }
  716.           }
  717.  
  718.       But then you lose the    vertical alignment of the regular
  719.       expressions.
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  731.  
  732.  
  733.  
  734.       AAAArrrreeee PPPPeeeerrrrllll rrrreeeeggggeeeexxxxppppssss DDDDFFFFAAAAssss    oooorrrr NNNNFFFFAAAAssss????  AAAArrrreeee tttthhhheeeeyyyy PPPPOOOOSSSSIIIIXXXX ccccoooommmmpppplllliiiiaaaannnntttt????
  735.  
  736.       While    it's true that Perl's regular expressions resemble the
  737.       DFAs (deterministic finite automata) of the _e_g_r_e_p(1)
  738.       program, they    are in fact implemented    as NFAs    (non-
  739.       deterministic    finite automata) to allow backtracking and
  740.       backreferencing.  And    they aren't POSIX-style    either,
  741.       because those    guarantee worst-case behavior for all cases.
  742.       (It seems that some people prefer guarantees of consistency,
  743.       even when what's guaranteed is slowness.)  See the book
  744.       "Mastering Regular Expressions" (from    O'Reilly) by Jeffrey
  745.       Friedl for all the details you could ever hope to know on
  746.       these    matters    (a full    citation appears in the    _p_e_r_l_f_a_q_2
  747.       manpage).
  748.  
  749.       WWWWhhhhaaaatttt''''ssss wwwwrrrroooonnnngggg wwwwiiiitttthhhh uuuussssiiiinnnngggg ggggrrrreeeepppp oooorrrr mmmmaaaapppp iiiinnnn aaaa vvvvooooiiiidddd    ccccoooonnnntttteeeexxxxtttt????
  750.  
  751.       Both grep and    map build a return list, regardless of their
  752.       context.  This means you're making Perl go to    the trouble of
  753.       building up a    return list that you then just ignore.    That's
  754.       no way to treat a programming    language, you insensitive
  755.       scoundrel!
  756.  
  757.       HHHHoooowwww ccccaaaannnn IIII mmmmaaaattttcccchhhh ssssttttrrrriiiinnnnggggssss wwwwiiiitttthhhh mmmmuuuullllttttiiiibbbbyyyytttteeee cccchhhhaaaarrrraaaacccctttteeeerrrrssss????
  758.  
  759.       This is hard,    and there's no good way.  Perl does not
  760.       directly support wide    characters.  It    pretends that a    byte
  761.       and a    character are synonymous.  The following set of
  762.       approaches was offered by Jeffrey Friedl, whose article in
  763.       issue    #5 of The Perl Journal talks about this    very matter.
  764.  
  765.       Let's    suppose    you have some weird Martian encoding where
  766.       pairs    of ASCII uppercase letters encode single Martian
  767.       letters (i.e.    the two    bytes "CV" make    a single Martian
  768.       letter, as do    the two    bytes "SG", "VS", "XX",    etc.). Other
  769.       bytes    represent single characters, just like ASCII.
  770.  
  771.       So, the string of Martian "I am CVSGXX!" uses    12 bytes to
  772.       encode the nine characters 'I', ' ', 'a', 'm', ' ', 'CV',
  773.       'SG',    'XX', '!'.
  774.  
  775.       Now, say you want to search for the single character /GX/.
  776.       Perl doesn't know about Martian, so it'll find the two bytes
  777.       "GX" in the "I am CVSGXX!"  string, even though that
  778.       character isn't there: it just looks like it is because "SG"
  779.       is next to "XX", but there's no real "GX".  This is a    big
  780.       problem.
  781.  
  782.       Here are a few ways, all painful, to deal with it:
  783.  
  784.  
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  797.  
  798.  
  799.  
  800.          $martian =~ s/([A-Z][A-Z])/ $1 /g;    # Make sure adjacent ``martian'' bytes
  801.                         # are no longer    adjacent.
  802.          print "found GX!\n" if $martian =~    /GX/;
  803.  
  804.       Or like this:
  805.  
  806.          @chars = $martian =~ m/([A-Z][A-Z]|[^A-Z])/g;
  807.          # above is    conceptually similar to:     @chars = $text =~ m/(.)/g;
  808.          #
  809.          foreach $char (@chars) {
  810.          print "found GX!\n", last if $char eq 'GX';
  811.          }
  812.  
  813.       Or like this:
  814.  
  815.          while ($martian =~    m/\G([A-Z][A-Z]|.)/gs) {  # \G probably    unneeded
  816.          print "found GX!\n", last if $1 eq 'GX';
  817.          }
  818.  
  819.       Or like this:
  820.  
  821.          die "sorry, Perl doesn't (yet) have Martian support )-:\n";
  822.  
  823.       In addition, a sample    program    which converts half-width to
  824.       full-width katakana (in Shift-JIS or EUC encoding) is
  825.       available from CPAN as
  826.  
  827.       There    are many double- (and multi-) byte encodings commonly
  828.       used these days.  Some versions of these have    1-, 2-,    3-,
  829.       and 4-byte characters, all mixed.
  830.  
  831.      AAAAUUUUTTTTHHHHOOOORRRR AAAANNNNDDDD    CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  832.       Copyright (c)    1997, 1998 Tom Christiansen and    Nathan
  833.       Torkington.  All rights reserved.
  834.  
  835.       When included    as part    of the Standard    Version    of Perl, or as
  836.       part of its complete documentation whether printed or
  837.       otherwise, this work may be distributed only under the terms
  838.       of Perl's Artistic License.  Any distribution    of this    file
  839.       or derivatives thereof _o_u_t_s_i_d_e of that package require that
  840.       special arrangements be made with copyright holder.
  841.  
  842.       Irrespective of its distribution, all    code examples in this
  843.       file are hereby placed into the public domain.  You are
  844.       permitted and    encouraged to use this code in your own
  845.       programs for fun or for profit as you    see fit.  A simple
  846.       comment in the code giving credit would be courteous but is
  847.       not required.
  848.  
  849.  
  850.  
  851.  
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLFFFFAAAAQQQQ6666((((1111))))
  863.  
  864.  
  865.  
  866.  
  867.  
  868.  
  869.  
  870.  
  871.  
  872.  
  873.  
  874.  
  875.  
  876.  
  877.  
  878.  
  879.  
  880.  
  881.  
  882.  
  883.  
  884.  
  885.  
  886.  
  887.  
  888.  
  889.  
  890.  
  891.  
  892.  
  893.  
  894.  
  895.  
  896.  
  897.  
  898.  
  899.  
  900.  
  901.  
  902.  
  903.  
  904.  
  905.  
  906.  
  907.  
  908.  
  909.  
  910.  
  911.  
  912.  
  913.  
  914.  
  915.  
  916.  
  917.  
  918.      Page 14                        (printed 10/23/98)
  919.  
  920.  
  921.  
  922.  
  923.  
  924.  
  925.